package com.aispeech.imgany;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.aispeech.imgany.data.TaobaoItem;
import com.aispeech.imgany.engineSdk.MyEngineListener;
import com.aispeech.imgany.engineSdk.VoiceEngineManage;
import com.aispeech.imgany.net.IPostImgListener;
import com.aispeech.imgany.net.PostImg;
import com.aispeech.imgany.ui.ScreenShotUtil;
import com.aispeech.imgany.ui.SelfDurationToast;
import com.aispeech.imgany.ui.ToastUtil;
import com.androidyuan.lib.screenshot.ScreenShotActivity;

import java.io.File;
import java.nio.channels.NonReadableChannelException;
import java.util.HashMap;
import java.util.List;
import java.util.Random;


/**
 * @author rain  01.24 2018
 */

public class ControlService extends Service {

    private final static String TAG = "ControlService";
    private MyReceive mbcr;
    public static String currentWakeupWord = "";//记录当前是哪个唤醒词被触发了
    private String[] wkTips = {
            "嗨",
            "你好啊",
            "恩哼",
            "怎么啦",
            "你在叫我吗",
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: release ....... !");
        VoiceEngineManage.getInstance().destroyEngine();
        unregisterReceiver(mbcr);
        deleteShotImgFile();
    }

    /**
     * 删除截屏文件
     */
    private void deleteShotImgFile() {
        String p = this.getExternalFilesDir("screenshot").getAbsolutePath();
        Log.d(TAG, "deleteShotImgFile path = " + p);
        File f = new File(p);
        f.delete();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand with:  flags = " + flags + ", startId = " + startId + "");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
        initReceiver();
        initVoiceEngine();

        ScreenShotUtil.getInstance().init(this);
    }


    private void initVoiceEngine() {
        Log.d(TAG, "initVoiceEngine: ");
        VoiceEngineManage.getInstance().initAllEngine(new MyEngineListener() {
            @Override
            public void onAsrResult(String result, boolean isFinish) {
                Log.d(TAG, "onAsrResult with: result = " + result + ", isFinish = " + isFinish + "");
                if (isFinish) {
//                    FloatWindowManager.getInstance().handleMessage(VoiceStateType.resumeDanmaku, result);
                    if ("asr_error".equals(result)) {
                        VoiceEngineManage.getInstance().playTTS("抱歉! 识别结果无法加载,请稍后尝试!");
                        return;
                    }
                    if (result.endsWith("取消") || result.endsWith("退出") || result.endsWith("不发了")) {
                        VoiceEngineManage.getInstance().playTTS("已取消!");
                        return;
                    }
//                    FloatWindowManager.getInstance().handleMessage(VoiceStateType.sendDanmaku, result);
//                    FloatWindowManager.getInstance().handleMessage(VoiceStateType.input, "");
                } else {
//                    FloatWindowManager.getInstance().handleMessage(VoiceStateType.input, result);
                }
            }

            @Override
            public void onWakeupResult(String result) {
                Log.d(TAG, "onWakeupResult with: result = " + result + "");
                currentWakeupWord = result;

                switch (result) {
                    case "ni hao xiao dou":
                        Random random = new Random();
                        int idx = random.nextInt(wkTips.length);
                        VoiceEngineManage.getInstance().playTTS(wkTips[idx]);
//                        VoiceEngineManage.getInstance().startWakeup();
                        break;

                    case "zhe shi shen me":
                        VoiceEngineManage.getInstance().playTTS("请稍等,让我看看");
//                        VoiceEngineManage.getInstance().startWakeup();
                        tryScreenShot();
                        break;
                    case "zhe shi shui":
                        VoiceEngineManage.getInstance().playTTS("请稍等,让我看下");
//                        VoiceEngineManage.getInstance().startWakeup();
                        tryScreenShot();
                        break;

                    case "zhe shi na":
                        VoiceEngineManage.getInstance().playTTS("请稍等,让我想想");
//                        VoiceEngineManage.getInstance().startWakeup();
                        tryScreenShot();
                        break;
                    case "tao bao tong kuan":
                        VoiceEngineManage.getInstance().playTTS("请稍等,让我找找");
                        tryScreenShot();
                        break;
                    case "cha kan xiang qing":
//                        VoiceEngineManage.getInstance().startWakeup();
                        if (SelfDurationToast.isIsToastAlive()) {
                            ScreenShotUtil.getInstance().initDataContent(MyApplication.getContext());
                            ScreenShotUtil.getInstance().showDataContent();
                            SelfDurationToast.handleHide();
                        }
                        break;
                    case "tui chu":
//                        VoiceEngineManage.getInstance().startWakeup();
                        if (ScreenShotUtil.getInstance().isContentAlive()) {
                            ScreenShotUtil.getInstance().dismissDataContent();
                        }
                        break;
                    case "di yi ge":
                    case "di er ge":
                    case "di san ge":
                        if (ScreenShotUtil.getInstance().isContentAlive()) {
                            List<TaobaoItem> taobaoList = ScreenShotUtil.getInstance().getTaobaoList();
                            if (taobaoList.size() > 0) {
                                String tts = "";
                                String detailUrl = "";
                                if (result.equals("di yi ge")) {
                                    TaobaoItem taobaoItem = taobaoList.get(0);

                                    String commentCount = taobaoItem.getCommentCount();
                                    detailUrl = taobaoItem.getDtlUrl();
                                    String itemLoc = taobaoItem.getItemLoc();
                                    String viewSales = taobaoItem.getViewSales();

                                    tts = "该宝贝" + "有" + viewSales + "、" + commentCount + "条评论、"
                                        + "商家地址在 " + itemLoc + " 、您还可以打开淘宝扫描二维码查看宝贝详情哦!";

                                } else if ("di er ge".equals(result) && taobaoList.size() > 1) {
                                    TaobaoItem taobaoItem = taobaoList.get(1);
                                    String commentCount = taobaoItem.getCommentCount();
                                    detailUrl = taobaoItem.getDtlUrl();
                                    String itemLoc = taobaoItem.getItemLoc();
                                    String viewSales = taobaoItem.getViewSales();

                                    tts = "该宝贝" + "有" + viewSales + "、" + commentCount + "条评论"
                                        + "商家地址在 " + itemLoc + " 、您还可以打开淘宝扫描二维码查看宝贝详情哦!";
                                } else if ("di san ge".equals(result) && taobaoList.size() > 2) {
                                    TaobaoItem taobaoItem = taobaoList.get(2);
                                    String commentCount = taobaoItem.getCommentCount();
                                    detailUrl = taobaoItem.getDtlUrl();
                                    String itemLoc = taobaoItem.getItemLoc();
                                    String viewSales = taobaoItem.getViewSales();

                                    tts = "该宝贝" + "有" + viewSales + "、" + commentCount + "条评论"
                                        + "商家地址在 " + itemLoc + " 、您还可以打开淘宝扫描二维码查看宝贝详情哦!";
                                }

                                Log.d(TAG, "onWakeupResult: tts = " + tts);
                                Log.d(TAG, "onWakeupResult: detailurl = " + detailUrl);
                                VoiceEngineManage.getInstance().playTTS(tts);
                                //将url转二维码显示
                                ScreenShotUtil.getInstance().showQRCodeWithUrl(detailUrl);
                            } else {
                                VoiceEngineManage.getInstance().playTTS("没有宝贝详情哦");
                            }
                        }
                        break;
                    default:
                        showToast(result);
                        break;
                }
            }

            @Override
            public void onVoiceState(int state) {
                Log.d(TAG, "onVoiceState with: state = " + state + "");
                updateAvartarState(state);
            }

            @Override
            public void onInitResult(String result) {
                Log.d(TAG, "onInitResult with: result = " + result + "");

                if ("success".equals(result)) {
                    VoiceEngineManage.getInstance().playTTS("语音已启动!");
                    VoiceEngineManage.getInstance().startWakeup();
                }
                if ("error".equals(result)) {
                    showToast("语音组件启动失败!!!");
                }
            }
        }, this);
    }


    private void initReceiver() {
        Log.d(TAG, "initReceiver: ");
        mbcr = new MyReceive();
        IntentFilter filter = new IntentFilter();
        filter.addAction("screen.shot.result");
        this.registerReceiver(mbcr, filter);
    }

    private void tryScreenShot() {
        Log.d(TAG, "tryScreenShot: ");
        Intent intent = new Intent(this, ScreenShotActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
    }


    private void updateAvartarState(int state) {
        Log.d(TAG, "updateAvartar with: state = " + state + "");
//        FloatWindowManager.getInstance().handleMessage(state, "");
    }

    private void showToast(final String txt) {
        Log.d(TAG, "showToast with: txt = " + txt + "");
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
//                Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_SHORT).show();
            }
        });
    }


    class MyReceive extends BroadcastReceiver {

        private final String TAG = "MyReceive";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "onReceive: action = " + action);
            if ("screen.shot.result".equals(action)) {
                String imgpath = intent.getStringExtra("imgpath");
                Log.d(TAG, "onReceive: imgpath = " + imgpath);

                if (TextUtils.isEmpty(imgpath)) {
                    VoiceEngineManage.getInstance().playTTS("抱歉!暂时无法获取屏幕图片");
//                    VoiceEngineManage.getInstance().startWakeup();
                } else {
                    ScreenShotUtil.getInstance().ShotDone(imgpath);

                }

            }
        }
    }
}
